<template>
  <div class="app-container">
    <div class="search-container">
      <el-form class="form_container" ref="queryFormRef" :model="queryParams" label-width="auto" :inline="true">
        <el-form-item label="订单号" prop="orderId">
          <el-input v-model="queryParams.orderId" placeholder="请输入" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="渠道订单" prop="channelOrderId">
          <el-input v-model="queryParams.channelOrderId" placeholder="请输入" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="渠道" prop="channelIds">
          <el-select multiple clearable @keyup.enter="handleQuery" v-model="queryParams.channelIds" placeholder="请选择" style="width: 16rem">
            <el-option v-for="item in channelArr" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="订单状态" prop="orderStatusList">
          <el-select multiple clearable @keyup.enter="handleQuery" v-model="queryParams.orderStatusList" placeholder="请选择" style="width: 16rem">
            <el-option v-for="item in orderStatusArr" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="业务类型" prop="bizTypes">
          <el-select multiple clearable @keyup.enter="handleQuery" v-model="queryParams.bizTypes" placeholder="请选择" style="width: 16rem">
            <el-option v-for="item in bizTypeArr" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="订单类型" prop="orderTypes">
          <el-select multiple clearable @keyup.enter="handleQuery" v-model="queryParams.orderTypes" placeholder="请选择" style="width: 16rem">
            <el-option v-for="item in orderTypeArr" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="平台" prop="platformIds">
          <el-select multiple clearable @keyup.enter="handleQuery" v-model="queryParams.platformIds" placeholder="请选择" style="width: 16rem">
            <el-option v-for="item in platFormArr" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="车型" prop="vehicleTypeIds">
          <el-select filterable multiple clearable @keyup.enter="handleQuery" v-model="queryParams.vehicleTypeIds" placeholder="请选择" style="width: 16rem">
            <el-option v-for="item in carTypeArr" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="供应商" prop="supplierId">
          <el-select filterable clearable @keyup.enter="handleQuery" v-model="queryParams.supplierId" placeholder="请选择" style="width: 16rem">
            <el-option v-for="item in supplierOptions" :key="item.id" :label="item.companyName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="城市" prop="cityId">
          <el-select filterable clearable @keyup.enter="handleQuery" v-model="queryParams.cityId" placeholder="请选择" style="width: 16rem">
            <el-option v-for="item in cityOptions" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="用车时间">
          <el-date-picker
            style="width: 16rem"
            format="YYYY/MM/DD"
            value-format="YYYY-MM-DD"
            @change="handleUseTimeChange"
            v-model="useTimes"
            type="daterange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
          />
        </el-form-item>
        <el-form-item label="下单时间">
          <el-date-picker
            style="width: 16rem"
            format="YYYY/MM/DD"
            value-format="YYYY-MM-DD"
            @change="handleCreatedTimeChange"
            v-model="createdTimes"
            type="daterange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
          />
        </el-form-item>
        <el-form-item label="司机手机" prop="driverPhone">
          <el-input v-model="queryParams.driverPhone" placeholder="请输入" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="司机id" prop="driverId">
          <el-input v-model="queryParams.driverId" placeholder="请输入" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="乘客姓名" prop="passengerName">
          <el-input v-model="queryParams.passengerName" placeholder="请输入" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="乘客电话" prop="passengerPhone">
          <el-input v-model="queryParams.passengerPhone" placeholder="请输入" clearable @keyup.enter="handleQuery" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <template #icon><Search /></template>
            搜索
          </el-button>
          <el-button @click="handleResetQuery">
            <template #icon><Refresh /></template>
            重置
          </el-button>
          <el-button @click="handleExport" type="warning">
            <template #icon><Edit /></template>
            导出
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <div style="margin-bottom: 6px">
          <el-button v-hasPerm="['order/add/btn']" type="success" @click="handleAdd">
            <template #icon><Plus /></template>
            新增订单
          </el-button>
        </div>
        <el-tabs v-model="activeName" class="demo-tabs" @tab-change="handleClick">
          <el-tab-pane :label="`全部(${countForm.all})`" :name="0"></el-tab-pane>
          <el-tab-pane :name="3">
            <template #label>
              <span :style="{ color: countForm.create > 0 ? 'red' : 'inherit' }">{{ `待确认(${countForm.create})` }}</span>
            </template>
          </el-tab-pane>
          <el-tab-pane :label="`待改派(${countForm.assign})`" :name="4"></el-tab-pane>
          <el-tab-pane :label="`待服务(${countForm.bound})`" :name="5"></el-tab-pane>
          <el-tab-pane :label="`3小时内(${countForm.hour3})`" :name="8"></el-tab-pane>
          <el-tab-pane :label="`24小时内(${countForm.hour24})`" :name="9"></el-tab-pane>
          <el-tab-pane :label="`已完成(${countForm.finish})`" :name="6"></el-tab-pane>
          <el-tab-pane :label="`已取消(${countForm.cancel})`" :name="7"></el-tab-pane>
          <el-tab-pane :label="`公共抢单池(${countForm.pool})`" :name="1"></el-tab-pane>
          <el-tab-pane :label="`车队抢单池(${countForm.poolSupplier})`" :name="2"></el-tab-pane>
        </el-tabs>
      </template>
      <el-table v-loading="loading" :data="TableData" highlight-current-row row-key="id" @row-click="handleRowClick">
        <el-table-column label="订单号" min-width="220" align="center" prop="id">
          <template #default="scope">
            <el-popover placement="right-start" :width="340" trigger="hover">
              <div class="table_btn">
                <div class="copy solid">
                  <el-button type="primary" @click="handleCopy(scope.row)">复制</el-button>
                </div>
                <div class="order_id">订单号:{{ scope.row.id }}</div>
                <div>订单渠道:{{ channelEnum[scope.row.channelId] }}</div>
                <div class="">渠道订单:{{ scope.row.channelOrderId }}</div>
                <div class="info solid">
                  <div>乘客姓名:{{ scope.row.passengerName }}</div>
                  <div>乘客电话:{{ scope.row.passengerPhone }}</div>
                  <div>虚拟号码:{{ scope.row.virtualPhone }}</div>
                  <div>用车时间:{{ scope.row.useTime }}</div>
                  <div>用车城市:{{ scope.row.cityName }}</div>
                  <div>上车地址:{{ scope.row.fromName }}</div>
                  <div>下车地址:{{ scope.row.toName }}</div>
                  <div>车型:{{ scope.row.vehicleTypeName }}</div>
                  <div v-if="scope.row.estimateDistance">预估里程:{{ scope.row.estimateDistance }}公里</div>
                  <div v-if="scope.row.estimateDuration">预估时长:{{ scope.row.estimateDuration }}分钟</div>
                  <div v-if="scope.row.flightNo">航班号:{{ scope.row.flightNo }}</div>
                  <div v-if="scope.row.days">包车天数:{{ scope.row.days }}</div>
                  <div v-if="scope.row.dailyDuration">包车每日时长:{{ scope.row.dailyDuration }}</div>
                  <div v-if="scope.row.dailyDistance">包车每日里程:{{ scope.row.dailyDistance }}</div>
                  <div>延迟用车时间:{{ scope.row.delayTime }}分钟</div>
                </div>
                <div class="price">产品卖价:{{ scope.row.orderPrice }}</div>
                <div class="price">供应商价格:{{ scope.row.supplierPrice }}</div>
                <div class="price">司机价格:{{ scope.row.driverPrice }}</div>
              </div>
              <template #reference>
                <div style="color: #40a9ff; cursor: pointer">
                  {{ scope.row.id }}
                </div>
              </template>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column label="供应商名称" min-width="200" align="center" prop="supplierName">
          <template #default="scope">{{ scope.row.supplierNo }}-{{ scope.row.supplierName }}</template>
        </el-table-column>
        <el-table-column label="司机信息" align="center" min-width="80" prop="supplierName">
          <template #default="scope">
            <el-popover v-if="scope.row.driverInfo" placement="top-start" :width="200" trigger="hover">
              <div class="table_btn">
                <div>司机姓名:{{ scope.row.driverInfo.name }}</div>
                <div>司机电话:{{ scope.row.driverInfo.phone }}</div>
                <div>车牌:{{ scope.row.driverInfo.carNum }}</div>
                <div>车型:{{ scope.row.driverInfo.carBrand }}-{{ scope.row.driverInfo.carSeries }}-{{ scope.row.driverInfo.carColor }}</div>
              </div>
              <template #reference>
                <div style="color: #40a9ff; cursor: pointer">
                  {{ scope.row.driverInfo.name }}
                </div>
              </template>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column label="下单时间" min-width="154" align="center" prop="createTime"></el-table-column>
        <el-table-column label="用车时间" min-width="154" align="center" prop="useTime"></el-table-column>
        <el-table-column label="取消时间" min-width="154" align="center" prop="cancelTime"></el-table-column>
        <el-table-column label="路程信息" min-width="300" align="left">
          <template #default="scope">
            <div class="address_box">
              <div class="item">
                <div class="tag">起点</div>
                <div class="content">{{ scope.row.fromCityName }}-{{ scope.row.fromCityArea }}-{{ scope.row.fromName }}</div>
              </div>
              <div class="item">
                <div class="tag tag2">终点</div>
                <div class="content">{{ scope.row.toCityName }}-{{ scope.row.toCityArea }}-{{ scope.row.toName }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="订单状态" min-width="200" align="center">
          <template #default="scope">
            <div v-if="scope.row.status == '0'" style="color: #ef6813">{{ orderStatusEnum[scope.row.status] }}</div>
            <div v-else-if="scope.row.status == 1" style="color: #e822ad">{{ orderStatusEnum[scope.row.status] }}</div>
            <div v-else-if="scope.row.status == 2" style="color: #4095ec">{{ orderStatusEnum[scope.row.status] }}</div>
            <div v-else-if="scope.row.status == 3" style="color: #55d187">{{ orderStatusEnum[scope.row.status] }}</div>
            <div v-else style="color: red">{{ orderStatusEnum[scope.row.status] }}</div>
          </template>
        </el-table-column>
        <el-table-column label="订单来源" min-width="300" align="center">
          <template #default="scope">
            <div style="display: flex; justify-content: center">
              <div>{{ scope.row.cityName }}</div>
              <div>-{{ platFormEnum[scope.row.platformId] }}</div>
              <div>-{{ channelEnum[scope.row.channelId] }}</div>
              <div>-{{ orderTypeEnum[scope.row.orderType] }}</div>
              <div>-{{ scope.row.vehicleTypeName }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="订单价格" min-width="154" align="center" prop="orderPrice"></el-table-column>
        <el-table-column label="实付金额" min-width="154" align="center" prop="realPrice"></el-table-column>
        <el-table-column label="供应商价格" min-width="154" align="center" prop="supplierPrice"></el-table-column>
        <el-table-column label="司机价格" min-width="154" align="center" prop="driverPrice"></el-table-column>
        <el-table-column label="调价金额" min-width="154" align="center" prop="adjustPrice"></el-table-column>
        <el-table-column label="优惠金额" min-width="154" align="center" prop="discountPrice"></el-table-column>
        <el-table-column label="附加费用" min-width="154" align="center" prop="otherPrice"></el-table-column>
        <el-table-column label="预估价格" min-width="154" align="center" prop="estimatePrice"></el-table-column>
        <el-table-column label="取消费" min-width="154" align="center" prop="cancelPrice"></el-table-column>
        <el-table-column label="取消原因" min-width="154" align="center" prop="cancelReason"></el-table-column>
        <el-table-column label="代扣协议状态" min-width="154" align="center">
          <template #default="scope">
            <div v-if="scope.row.driverProtocolStatus == 0">待审核</div>
            <div v-else-if="scope.row.driverProtocolStatus == 1">通过</div>
            <div v-else-if="scope.row.driverProtocolStatus == 2">驳回</div>
          </template>
        </el-table-column>
        <el-table-column label="备注" min-width="154" align="center" prop="remark"></el-table-column>

        <el-table-column label="行李信息" min-width="400" align="center">
          <template #default="scope">
            <div style="display: flex; align-items: center; justify-content: center">
              <div v-if="scope.row.luggageType">{{ luggageEnum[scope.row.luggageType] }}-</div>
              <div v-if="scope.row.luggageNum">-行李数:{{ scope.row.luggageNum }}</div>
            </div>

            <template v-if="scope.row.luggageInfo">
              <div style="display: flex; align-items: center; justify-content: center" v-for="(item, index) in scope.row.luggageInfo" :key="index">
                <div>{{ item.code }}-{{ item.weight }}kg</div>
                <div v-for="(ele, i) in item.img.split(',')" :key="i">
                  <Image width="40px" height="40px" :src="ele" />
                </div>
              </div>
            </template>
          </template>
        </el-table-column>
        <el-table-column fixed="right" align="center" label="操作" width="220">
          <template #default="scope">
            <div style="display: flex; justify-content: center; align-items: center">
              <el-button v-hasPerm="['order/send/btn']" type="primary" link size="small" @click.stop="handleSend(scope.row)">
                <template #icon><Pointer /></template>
                改派
              </el-button>
              <el-dropdown @command="handleCommand($event, scope.row)">
                <a class="el-dropdown-link" style="color: #4080ff; margin-left: 4px">更多</a>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="1">订单日志</el-dropdown-item>
                    <el-dropdown-item command="2">其他操作</el-dropdown-item>
                    <el-dropdown-item command="3">奖惩</el-dropdown-item>
                    <el-dropdown-item command="4">行驶轨迹</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-if="total > 0" v-model:total="total" v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize" @pagination="handleQuery" />
    </el-card>
    <!-- 改派 -->
    <sendModal ref="sendModalRef" @success="handleSuccess" />
    <logModal ref="logModalRef" />
    <actionModal ref="actionModalRef" @success="handleSuccess" />
    <moneyModal ref="moneyModalRef" @success="handleSuccess" />
    <mapModal ref="mapModalRef" @success="handleSuccess" />
    <addModal ref="addModalRef" @success="handleSuccess" />
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "SysMenu",
  inheritAttrs: false,
});

import OrderApi from "@/api/order";
import CommonApi from "@/api/common";
import ExportApi from "@/api/exports";
import sendModal from "./components/sendModal.vue";
import logModal from "./components/logModal.vue";
import actionModal from "./components/actionModal.vue";
import moneyModal from "./components/moneyModal.vue";
import mapModal from "./components/mapModal.vue";
import addModal from "./components/addModal.vue";
import {
  orderStatusEnum,
  platFormEnum,
  channelEnum,
  orderTypeEnum,
  bizTypeEnum,
  luggageEnum,
  channelArr,
  orderStatusArr,
  bizTypeArr,
  orderTypeArr,
  platFormArr,
  carTypeArr,
} from "@/enums/common";
import { MenuTypeEnum } from "@/enums/MenuTypeEnum";
import { log } from "console";

const queryFormRef = ref(ElForm);
const total = ref(0);
const supplierOptions = ref();
const cityOptions = ref();
const useTimes = ref();
const createdTimes = ref();
const sendModalRef: any = ref(null); //改派
const logModalRef: any = ref(null); //日志
const actionModalRef: any = ref(null); //其他操作
const moneyModalRef: any = ref(null); //奖惩
const mapModalRef: any = ref(null); //轨迹
const addModalRef: any = ref(null); //新增
const activeName = ref(0);
const countForm = ref({
  all: undefined,
  create: undefined,
  assign: undefined,
  bound: undefined,
  hour3: undefined,
  hour24: undefined,
  finish: undefined,
  cancel: undefined,
  pool: undefined,
  poolSupplier: undefined,
}); //订单统计tabs
const handleClick = (tab: any) => {
  activeName.value = tab;
  queryParams.type = activeName.value;
  handleQuery();
};

const loading = ref(false);

// 查询参数
const queryParams: any = reactive({
  pageNo: 1,
  pageSize: 10,
});
// 菜单表格数据
const TableData = ref([]);

// 选择表格的行菜单ID
const selectedMenuId = ref<number | undefined>();

//新增订单
function handleAdd() {
  addModalRef.value.edit();
}
function handleExport() {
  ExportApi.orderExport(queryParams).then((res) => {
    let data = res.data;
    ElMessage.success("导出完毕");
    if (!data) {
      return;
    }
    if (typeof window.navigator.msSaveBlob !== "undefined") {
      window.navigator.msSaveBlob(new Blob([data], { type: "application/vnd.ms-excel" }), fileName + ".xls");
    } else {
      let url = window.URL.createObjectURL(new Blob([data], { type: "application/vnd.ms-excel" }));
      let link = document.createElement("a");
      link.style.display = "none";
      link.href = url;
      link.setAttribute("download", "订单" + ".xlsx");
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link); //下载完成移除元素
      window.URL.revokeObjectURL(url); //释放掉blob对象
    }
  });
}
//复制事件
function handleCopy(orderInfo: any) {
  const textToCopy = `
      【最新的订单来源】:${channelEnum[orderInfo.channelId]}
      订单号:${orderInfo.id}
      订单渠道:${channelEnum[orderInfo.channelId]}
      客户姓名:${orderInfo.passengerName}
      客户手机号:${orderInfo.passengerPhone}
      用车时间:${orderInfo.useTime}
      用车信息:${orderInfo.fromCityName}-${orderInfo.vehicleTypeName}
      套餐类型:${orderTypeEnum[orderInfo.orderType]}
      上车地址:${orderInfo.fromName}
      下车地址:${orderInfo.toName}
      预估里程:${orderInfo.estimateDistance}公里
      车型:${orderInfo.vehicleTypeName}
      航班号:${orderInfo.flightNo}
      用车结束后,麻烦提醒乘客好评
      联系乘客禁止索要乘客微信和真实电话号码，司机禁止透露自己微信或者真实电话如发现将视为切单严罚（客人主动索要也不允许）
      用车所产生额外超额费用，司机必须通过短信链接推送生成二维码让乘客线上支付，不准以任何理由线下收取，否则视为飞单，否则视为飞单，否则视为飞单。
      电话全程录音，电话全程录音，电话全程录音........
    `;
  const textarea = document.createElement("textarea");
  textarea.value = textToCopy;
  document.body.appendChild(textarea);
  textarea.select();
  document.execCommand("copy");
  document.body.removeChild(textarea);
  ElMessage.success("复制成功");
}
// 查询菜单
function handleQuery() {
  loading.value = true;
  OrderApi.getOrders(queryParams)
    .then((data: any) => {
      TableData.value = data.result;
      total.value = data.total * 1;
    })
    .finally(() => {
      loading.value = false;
    });
}

function handleSuccess() {
  handleQuery();
}
/**
 *
 * @param row 改派触发
 */
function handleSend(row: any) {
  sendModalRef.value.edit(row);
}

function handleCommand(type: any, row: any) {
  if (type == 1) {
    //日志
    logModalRef.value.edit(row);
  } else if (type == 2) {
    //其他操作
    actionModalRef.value.edit(row);
  } else if (type == 3) {
    //奖惩
    moneyModalRef.value.edit(row);
  } else {
    //行驶轨迹
    mapModalRef.value.edit(row);
  }
}
function handleUseTimeChange(time: any) {
  if (time) {
    queryParams.useTimeFrom = `${time[0]} 00:00:00`;
    queryParams.useTimeTo = `${time[1]} 23:59:59`;
  } else {
    queryParams.useTimeFrom = undefined;
    queryParams.useTimeTo = undefined;
  }
}
function handleCreatedTimeChange(time: any) {
  if (time) {
    queryParams.createTimeFrom = `${time[0]} 00:00:00`;
    queryParams.createTimeTo = `${time[1]} 23:59:59`;
  } else {
    queryParams.createTimeFrom = undefined;
    queryParams.createTimeFrom = undefined;
  }
}

// 重置查询
function handleResetQuery() {
  queryParams.useTimeFrom = undefined;
  queryParams.useTimeTo = undefined;
  queryParams.createTimeFrom = undefined;
  queryParams.createTimeTo = undefined;
  useTimes.value = null;
  createdTimes.value = null;

  queryFormRef.value.resetFields();
  queryParams.pageNo = 1;
  handleQuery();
}

// 行点击事件
function handleRowClick(row: MenuVO) {
  // 记录表格选择的菜单ID，新增子菜单作为父菜单ID
  selectedMenuId.value = row.id;
}

onMounted(() => {
  handleQuery();
  CommonApi.getSupplier({ pageNo: 1, pageSize: 9999, status: 1 }).then((data) => {
    if (data.code == 0) {
      supplierOptions.value = data.result;
    }
  });
  CommonApi.getCity({ pageNo: 1, pageSize: 9999 }).then((data: any) => {
    if (data.code == 0) {
      cityOptions.value = data.result;
    }
  });
  OrderApi.getOrderCount().then((data: any) => {
    if (data.code == 0) {
      countForm.value = data.result;
    }
  });
});
</script>
<style lang="scss" scoped>
.form_container {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}
.address_box {
  display: flex;
  flex-direction: column;
  align-items: left;
  justify-content: left;
  .item {
    display: flex;
    align-items: center;
    margin: 4px 0;
    .tag {
      width: 50px;
      height: 23px;
      text-align: center;
      color: orange;
      background: #fff8e6;
    }
    .tag2 {
      color: #3fd175;
      background: #e7faf0;
    }
  }
}
.table_btn {
  // width: 18vw;
  padding: 14px 0;
  line-height: 28px;
  .copy {
    display: flex;
    padding-bottom: 6px;
    .btn,
    .btn2 {
      border: 1px solid gray;
      margin-right: 6px;
      padding: 0px 6px;
      cursor: pointer;
    }
    .btn2 {
      border: 1px solid #1890ff;
      color: #1890ff;
    }
  }
  .order_id {
  }
  .info {
  }
  .price {
    margin-top: 8px;
  }
  .solid {
    border-bottom: 1px solid gray;
  }
}
</style>
